<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      http://www.dbshop.net/
 * @copyright Copyright (c) 2012-2016 DBShop.net Inc. (http://www.dbshop.net)
 * @license   http://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风
 *
 */

namespace Dbapi\Controller;

use Zend\Config\Reader\Ini;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Mvc\MvcEvent;

class JsonbaseController extends AbstractActionController
{
    protected $postData;    //post信息
    protected $getData;     //get信息
    protected $userData;    //会员信息

    protected $storageConfig;   //存储设置

    protected function attachDefaultListeners()
    {
        $events = $this->getEventManager();
        $events->attach(MvcEvent::EVENT_DISPATCH, array($this,'checkJsonApiKey'), 200);

        parent::attachDefaultListeners();
    }
    /**
     * api入口的一系列的验证处理
     * @param MvcEvent $e
     */
    public function checkJsonApiKey(MvcEvent $e)
    {
        //apikey可以get传递，也可以post传递
        $queryApiKey    = trim($_REQUEST['apikey']);

        if(!file_exists(DBSHOP_PATH . '/module/Extendapp/Dbapi/data/apiKey.php')) exit(json_encode(array('status'=>'error', 'message'=>'Api Key Error')));

        $apiArray       = include DBSHOP_PATH . '/module/Extendapp/Dbapi/data/apiKey.php';
        //查看是否关闭了api接口
        if(!isset($apiArray['dbshopApiState']) or (isset($apiArray['dbshopApiState']) and $apiArray['dbshopApiState'] != 1)) {
            header('Content-type: application/json');
            exit(json_encode(array('status'=>'success', 'msg'=>'Api Close')));
        }
        //检查是否接口调用的key相符
        if(!isset($apiArray['apiKey']) or (isset($apiArray['apiKey']) and empty($apiArray['apiKey'])) or $apiArray['apiKey'] !== $queryApiKey) {
            //发布时下面这句要去掉注释
            header('Content-type: application/json');
            exit(json_encode(array('status'=>'error', 'message'=>'Api Key Error')));
        }

        //检查是否过来的是微信小程序
        $apiClient = $this->request->getQuery('apiClient');
        if(!empty($apiClient) && $apiClient == 'smallWeixin') {
            $GLOBALS['apiClient'] = 'smallWeixin';
            $this->getServiceLocator()->get('frontHelper')->setFrontDefaultCurrency('CNY');
        }

        //获取post传值信息
        if($this->request->isPost()) {
            $this->postData = $this->request->getPost()->toArray();
        }
        //获取get传值信息
        if($this->request->isGet()) {
            $this->getData = $this->request->getQuery()->toArray();
        }
        //会员信息
        if(isset($this->postData['user_token']) or isset($this->getData['user_token'])) {
            $userToken = (isset($this->postData['user_token']) and !empty($this->postData['user_token'])) ? $this->postData['user_token'] : '';
            if(empty($userToken)) $userToken = (isset($this->getData['user_token']) and !empty($this->getData['user_token'])) ? $this->getData['user_token'] : '';

            if(!empty($userToken)) {
                $LoginInfo = $this->getServiceLocator()->get('ApiUserLoginTable')->infoUserLogin(array('user_token'=>$userToken));
                if(!empty($LoginInfo) and isset($LoginInfo->user_serialize) and !empty($LoginInfo->user_serialize)) {
                    $this->userData = unserialize($LoginInfo->user_serialize);
                    $this->userData['user_avatar'] = $this->createDbshopImageUrl($this->userData['user_avatar']);
                }
            }
        }

        //对需要判断会员是否登录的action进行处理
        $actionName = $e->getRouteMatch()->getParam('action');
        $checkUserLoginActionArray = array(
            'statistics',           //统计信息
            'loginState',           //登录状态
            'addGoodsFavorites',    //收藏商品
            'addressList',          //配送地址列表
            'saveAddress',          //增加或者更新配送地址信息
            'delAddress',           //删除配送地址信息
            'step',                 //订单确认
            'cartSubmit',           //订单提交
            'userInfo',             //获取会员信息
            'saveUser',             //保存会员信息
            'saveUserPasswd',       //修改会员密码
            'favoritesGoods',       //会员收藏列表
            'delFavoritesGoods',    //会员收藏商品删除
            'homeGoodsAsk',         //会员中心，我的咨询
            'homeGoodsAskDel',      //会员中心，我的咨询删除
            'newOrder',             //获取最新会员订单列表
            'orderList',            //获取会员订单列表
            'showOrder',            //获取会员订单详情
            'cancelOrder',          //会员取消订单
            'delOrder',             //会员删除订单
            'submitRefundOrderGoods',//订单商品退货申请
            'listRefundOrderGoods', //订单商品退货列表
            'listOrderGoods',       //订单商品列表
            'orderGoodsComment',    //订单商品评价
            'submitOrderGoodsComment',//提交订单商品评价
            'orderAppPay',          //api订单支付调用
            'orderPayFinish',       //订单完成付款
            'orderReceipt',         //订单确认收货
            'paymentInfo',          //获取支付信息
        );
        if(!empty($actionName) and in_array($actionName, $checkUserLoginActionArray) and $this->userData['user_id'] <= 0) {
            header('Content-type: application/json');
            $loginResult = array(
                'status'=> 'error',
                'code'  => 201,
                'msg'   => '该会员未登录！'
            );
            //JSON_UNESCAPED_UNICODE 参数在PHP5.4中才被加入
            if (version_compare(phpversion(), '5.4', '<') === true) {
                echo json_encode($loginResult);
                exit();
            }
            echo json_encode($loginResult, JSON_UNESCAPED_UNICODE);
            exit();
        }

        //存储设置信息
        $iniReader = new Ini();
        $this->storageConfig = $iniReader->fromFile(DBSHOP_PATH . '/data/moduledata/Upload/Storage.ini');
    }
    /**
     * 将图片替换为url的形式访问
     * @param $image
     * @param bool|true $goodsIsImage
     * @return mixed|string
     */
    public function createDbshopImageUrl($image, $goodsIsImage=true)
    {
        $dbshopPath = $_SERVER['PHP_SELF'] ? dirname($_SERVER['PHP_SELF']) : dirname($_SERVER['SCRIPT_NAME']);
        $dbshopPath = ($dbshopPath == '/' ? '' : $dbshopPath);

        $qiniuHttp  = (isset($this->storageConfig['qiniu_http_type']) ? $this->storageConfig['qiniu_http_type'] : 'http://');
        $aliyunHttp = (isset($this->storageConfig['aliyun_http_type']) ? $this->storageConfig['aliyun_http_type'] : 'http://');

        if(stripos($image, '{qiniu}') !== false) return str_replace('{qiniu}', $qiniuHttp.$this->storageConfig['qiniu_domain'], $image);
        if(stripos($image, '{aliyun}') !== false) return str_replace('{aliyun}', $aliyunHttp.$this->storageConfig['aliyun_domain'], $image);
        if(stripos($image, 'http://') !== false or stripos($image, 'https://') !== false) return $image;

        if(defined('FRONT_CDN_STATE') and FRONT_CDN_STATE == 'true' and $goodsIsImage) {//开启cdn图片加速
            if(stripos($image, 'http') === false) {
                //判断在开启cdn时，如果没有图片，输出默认图片
                if($image == '' or !file_exists(DBSHOP_PATH . $image)) $image = $this->getServiceLocator()->get('frontHelper')->getGoodsUploadIni('goods', 'goods_image_default');

                if(isset($GLOBALS['apiClient']) && $GLOBALS['apiClient'] == 'smallWeixin' && stripos(FRONT_CDN_HTTP_TYPE, 'http://') !== false) {
                    return $this->getServiceLocator()->get('frontHelper')->dbshopHttpOrHttps() . $this->getServiceLocator()->get('frontHelper')->dbshopHttpHost() . $dbshopPath . $image;
                }

                return FRONT_CDN_HTTP_TYPE . FRONT_CDN_DOMAIN . $dbshopPath . $image;
            }
        }

        if($image == '' or !file_exists(DBSHOP_PATH . $image)) $image = $this->getServiceLocator()->get('frontHelper')->getGoodsUploadIni('goods', 'goods_image_default');
        $url = $this->getServiceLocator()->get('frontHelper')->dbshopHttpOrHttps() . $this->getServiceLocator()->get('frontHelper')->dbshopHttpHost() . $dbshopPath . $image;

        return $url;

    }
}